/**
 * jims
 */
package com.jims.master.modules.csm.service;

import com.jims.master.common.config.Global;
import com.jims.master.common.data.StringData;
import com.jims.master.common.persistence.BaseEntity;
import com.jims.master.common.persistence.Page;
import com.jims.master.common.service.CrudService;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.modules.csm.dao.*;
import com.jims.master.modules.csm.entity.*;
import com.jims.master.modules.oper.dao.ClinicItemDictDao;
import com.jims.master.modules.oper.dao.ClinicVsChargeDao;
import com.jims.master.modules.oper.dao.PriceListDao;
import com.jims.master.modules.oper.dao.PriceListLogDao;
import com.jims.master.modules.oper.entity.ClinicItemDict;
import com.jims.master.modules.oper.entity.ClinicVsCharge;
import com.jims.master.modules.oper.entity.PriceList;
import com.jims.master.modules.oper.entity.PriceListLog;
import com.jims.master.modules.sys.utils.UserUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 消耗品价格Service
 *
 * @author CTQ
 * @version 2017-03-02
 */
@Service
@Transactional(readOnly = true)
public class ExpPriceService extends CrudService<ExpPriceDao, ExpPrice> {
    @Autowired
    private PriceListDao priceListDao;
    @Autowired
    private PriceListLogDao priceListLogDao;
    @Autowired
    private ExpDictDao expDictDao;
    @Autowired
    private ExpPriceLogDao expPriceLogDao;
    @Autowired
    private ExpNameDictDao expNameDictDao;
    @Autowired
    private ExpInfoDao expInfoDao;
    @Autowired
    private ExpStockDao expStockDao;
    @Autowired
    private ClinicItemDictDao clinicItemDictDao;
    @Autowired
    private ClinicVsChargeDao clinicVsChargeDao;

    public ExpPrice get(String id) {
        return super.get(id);
    }

    public List<ExpPrice> findList(ExpPrice expPrice) {
        return super.findList(expPrice);
    }


    /**
     * 查询现行价格
     *
     * @param page
     * @param expPrice
     * @return
     */
    public Page<ExpPrice> findListPrice(Page<ExpPrice> page, ExpPrice expPrice) {

        expPrice.setPage(page);
        page.setList(dao.findListPrice(expPrice));
        return page;
    }

    /**
     * 查询历史价格
     *
     * @param page
     * @param expPrice
     * @return
     */

    public Page<ExpPrice> findListPriceLog(Page<ExpPrice> page, ExpPrice expPrice) {
        expPrice.setPage(page);
        page.setList(dao.findListPriceLog(expPrice));
        return page;
    }

    @Transactional(readOnly = false)
    public int savePrice(ExpPrice expPrice) {
        ExpPrice oldPrice = new ExpPrice();
        ExpInfo oldInfo = new ExpInfo();
        oldInfo.setId(expPrice.getExpInfo().getId());
        oldPrice.setExpInfo(oldInfo);
        List<ExpPrice> list = dao.findByExpInfo(oldPrice);
        if(null != list && list.size() > 0){
            return -1;
        }
        int num = 0;
        if (StringUtils.isNotBlank(expPrice.getId())) {//修改
            /**处理价表**/
            if (StringUtils.isNotBlank(expPrice.getPriceList().getId())) {
                PriceList pl = priceListDao.get(expPrice.getPriceList().getId());
                PriceList priceList = handlePriceList(expPrice, pl);
                priceList.preUpdate();
                priceListDao.update(priceList);
            }
            /**处理消耗品价格**/
            expPrice.preUpdate();
            num = dao.update(expPrice);
            /**一般的修改不处理exp_price_log记录表**/

        } else {//新增
            /**处理价表**/
            PriceList priceList = handlePriceList(expPrice, new PriceList());
            priceList.setItemClass("I");
            priceList.preInsert();
            priceListDao.insert(priceList);
            PriceListLog priceListLog = handlePriceListLog(priceList);
            priceListLog.preInsert();
            priceListLogDao.insert(priceListLog);
            /**处理消耗品价格**/
            expPrice.setOrgId(UserUtils.getOrgId());
            expPrice.setPriceList(priceList);
            expPrice.preInsert();
            expPrice.setId(priceList.getId());
            num = dao.insert(expPrice);
            /**消耗品价格记录**/
            handleExpPriceLog(expPrice, priceList);

            //生成clinicItemDict表
            ClinicItemDict clinicItemDict = new ClinicItemDict();
            clinicItemDict.setItemClass(priceList.getItemClass());        // 诊疗项目分类
            clinicItemDict.setItemCode(priceList.getItemCode());        // 诊疗代码
            clinicItemDict.setItemName(priceList.getItemName());        // 诊疗项目名称
            clinicItemDict.setInputCode(priceList.getInputCode());        // 拼音码
            clinicItemDict.setPrice(priceList.getPrice());          //总价
            clinicItemDict.setPreferPrice(priceList.getPreferPrice());    //优惠价格
            clinicItemDict.updateOrgId();
            clinicItemDict.preInsert();
            clinicItemDict.setId(priceList.getId());
            clinicItemDictDao.insert(clinicItemDict);
            //生成clinicVsCharge表
            ClinicVsCharge clinicVsCharge = new ClinicVsCharge();
            clinicVsCharge.setAmount("1");
            clinicVsCharge.setChargeId(priceList.getId());
            clinicVsCharge.setClinicId(clinicItemDict.getId());
            clinicVsCharge.preInsert();
            clinicVsChargeDao.insert(clinicVsCharge);
        }
        return num;
    }

    /**
     * 处理价表
     *
     * @param expPrice
     * @param priceList
     * @return
     * @author CTQ
     */
    private PriceList handlePriceList(ExpPrice expPrice, PriceList priceList) {
        ExpDict expDict = new ExpDict();
        String expId = expPrice.getExpInfo().getExpDict().getId();
        if (StringUtils.isNotBlank(expId)) {
            expDict = expDictDao.get(expId);
        }
        ExpNameDict expNameDict = expNameDictDao.findByExpCode(expDict.getExpCode());
        if (expNameDict != null) {
            priceList.setItemClass("I");
        }
        priceList.setItemName(expDict.getExpName());
        priceList.setItemCode(expDict.getExpCode());
        priceList.setItemSpec(expPrice.getPackageSpec());
        priceList.setUnits(expPrice.getUnits());
        priceList.setInputCode(expDict.getInputCode());
        priceList.setOrgId(UserUtils.getOrgId());
        priceList.setClassOnMr(expPrice.getClassOnMr());
        priceList.setClassOnRcpt(expPrice.getClassOnRcpt());
        priceList.setClassOnReckoning(expPrice.getClassOnReckoning());
        priceList.setSubjCode(expPrice.getSubjCode());
        priceList.setStartDate(new Date());
        priceList.setPrice(expPrice.getRetailPrice());
        priceList.setPreferPrice(expPrice.getRetailPrice());

        return priceList;
    }

    /**
     * 处理价表日志
     *
     * @param priceList
     * @return
     * @author CTQ
     */
    private PriceListLog handlePriceListLog(PriceList priceList) {
        PriceListLog log = new PriceListLog();
        log.setOrgId(priceList.getOrgId());
        log.setInputCode(priceList.getInputCode());
        log.setClassOnMr(priceList.getClassOnMr());
        log.setClassOnRcpt(priceList.getClassOnRcpt());
        log.setClassOnReckoning(priceList.getClassOnReckoning());
        log.setIsNer(Global.YES);
        log.setItemClass(priceList.getItemClass());
        log.setItemCode(priceList.getItemCode());
        log.setItemName(priceList.getItemName());
        log.setItemSpec(priceList.getItemSpec());
        log.setPreferPrice(priceList.getPreferPrice());
        log.setPrice(priceList.getPrice());
        log.setPriceId(priceList.getId());
        log.setStartDate(priceList.getStartDate());
        log.setStopDate(priceList.getStopDate());
        log.setSubjCode(priceList.getSubjCode());
        log.setUnits(priceList.getUnits());
        return log;
    }

    /**
     * 消耗品价格记录--一般的消耗品修改不调用此方法，调价，停价才处理此表数据
     *
     * @param expPrice
     * @param priceList
     * @author CTQ
     */
    private void handleExpPriceLog(ExpPrice expPrice, PriceList priceList) {
        ExpPriceLog expPriceLog = new ExpPriceLog();
        expPriceLog.setExpInfo(expPrice.getExpInfo().getId());
        expPriceLog.setStartDate(expPrice.getStartDate());
        expPriceLog.setPackageSpec(expPrice.getPackageSpec());
        expPriceLog.setUnits(expPrice.getUnits());
        expPriceLog.setSubjCode(expPrice.getSubjCode());
        expPriceLog.setOrgId(expPrice.getOrgId());
        expPriceLog.setClassOnMr(expPrice.getClassOnMr());
        expPriceLog.setClassOnRcpt(expPrice.getClassOnRcpt());
        expPriceLog.setClassOnReckoning(expPrice.getClassOnReckoning());
        expPriceLog.setExpPriceId(expPrice.getId());
        expPriceLog.setPriceId(priceList.getId());
        expPriceLog.setPriceMax(expPrice.getPriceMax());
        expPriceLog.setRetailPrice(expPrice.getRetailPrice());
        expPriceLog.setTradePrice(expPrice.getTradePrice());
        expPriceLog.setStopDate(expPrice.getStopDate());
        expPriceLog.setIsNew(Global.YES);
        expPriceLog.preInsert();
        expPriceLogDao.insert(expPriceLog);
    }

    /**
     * 生成基本价格
     * @param expPrice
     * @return
     */
    @Transactional(readOnly = false)
    public int basicPrice(ExpPrice expPrice) {
        int num = 0;
        if (expPrice != null) {
            expPrice = dao.get(expPrice);
            if (StringUtils.isNotBlank(expPrice.getPackageSpec())) {
                /**1.判断本条消耗品价格是否是基本价格**/
                if (expPrice.getPackageSpec().contains("*")) {
                    ExpInfo expInfo = expInfoDao.get(expPrice.getExpInfo());
                    /**2.判断基本价格是否已生成**/
                    expPrice.setPackageSpec(expInfo.getMinSpec());
                    expPrice.setUnits(expInfo.getMinUnits());
                    expPrice.updateOrgId();
                    List<ExpPrice> list = dao.findByMinSpec(expPrice);
                    if (list != null && list.size() > 0) {
                        num = -1;//说明基本价格已生成
                    } else {
                        Double number = Double.valueOf(expInfo.getPackageNum());
                        double minTradePrice = expPrice.getTradePrice() / number;
                        minTradePrice = (double)Math.round(minTradePrice * 100) / 100;
                        double minRetailPrice = expPrice.getRetailPrice() / number;
                        minRetailPrice = (double)Math.round(minRetailPrice * 100) / 100;
                        expPrice.setTradePrice(expPrice.getTradePrice() / number);
                        expPrice.setRetailPrice(expPrice.getRetailPrice() / number);
                        if(null != expPrice.getPriceMax()){
                            expPrice.setPriceMax(expPrice.getPriceMax() / number);
                        }else{
                            expPrice.setPriceMax(null);
                        }

                        /**处理价表**/
                        PriceList priceList = handlePriceList(expPrice, new PriceList());
                        priceList.preInsert();
                        priceListDao.insert(priceList);
                        PriceListLog priceListLog = handlePriceListLog(priceList);
                        priceListLog.preInsert();
                        priceListLogDao.insert(priceListLog);
                        /**处理消耗品价格**/
                        expPrice.setPriceList(priceList);
                        expPrice.preInsert();
                        expPrice.setId(priceList.getId());
                        num = dao.insert(expPrice);
                        /**消耗品价格记录**/
                        handleExpPriceLog(expPrice, priceList);
                        //生成clinicItemDict表
                        ClinicItemDict clinicItemDict = new ClinicItemDict();
                        clinicItemDict.setItemClass(priceList.getItemClass());        // 诊疗项目分类
                        clinicItemDict.setItemCode(priceList.getItemCode());        // 诊疗代码
                        clinicItemDict.setItemName(priceList.getItemName());        // 诊疗项目名称
                        clinicItemDict.setInputCode(priceList.getInputCode());        // 拼音码
                        clinicItemDict.setPrice(priceList.getPrice());          //总价
                        clinicItemDict.setPreferPrice(priceList.getPreferPrice());    //优惠价格
                        clinicItemDict.updateOrgId();
                        clinicItemDict.preInsert();
                        clinicItemDict.setId(priceList.getId());
                        clinicItemDictDao.insert(clinicItemDict);
                        //生成clinicVsCharge表
                        ClinicVsCharge clinicVsCharge = new ClinicVsCharge();
                        clinicVsCharge.setAmount("1");
                        clinicVsCharge.setChargeId(priceList.getId());
                        clinicVsCharge.setClinicId(clinicItemDict.getId());
                        clinicVsCharge.preInsert();
                        clinicVsChargeDao.insert(clinicVsCharge);
                    }
                } else {
                    num = 0;
                }
            }
        }
        return num;
    }

    @Transactional(readOnly = false)
    public int savePriceModify(ExpPrice expPrice) {
        int num = 1;
        //带*为复数的包装，修改价格时同步修改最小包装的价格
//        expPrice = dao.get(expPrice);
        ExpInfo expInfo = expInfoDao.get(expPrice.getExpInfo());

        //判断是不是大包装
        if (expPrice.getPackageSpec().contains("*")) {

            //获取最小包装的价格
            ExpPrice expPriceMinSpec = new ExpPrice();
            expPriceMinSpec.setExpInfo(expPrice.getExpInfo());
            expPriceMinSpec.setPackageSpec(expInfo.getMinSpec());
            expPriceMinSpec.setUnits(expInfo.getMinUnits());
            expPriceMinSpec.updateOrgId();
            List<ExpPrice> priceMinSpec = dao.findByMinSpec(expPriceMinSpec);

            //判断有没有小包装
            if (priceMinSpec.size() == 1) {
                expPriceMinSpec = priceMinSpec.get(0);
                expPriceMinSpec.setTradePrice(expPrice.getTradePrice() / expInfo.getPackageNum());
                expPriceMinSpec.setRetailPrice(expPrice.getRetailPrice() / expInfo.getPackageNum());
                num = expPriceModify(expPrice, expPriceMinSpec, expInfo, num);
            }
            ExpPrice expPriceMaxSpec = dao.get(expPrice);
            expPriceMaxSpec.setTradePrice(expPrice.getTradePrice());
            expPriceMaxSpec.setRetailPrice(expPrice.getRetailPrice());
            num = expPriceModify(expPrice, expPriceMaxSpec, expInfo, num);
        } else {
            ExpPrice expPriceOld = dao.get(expPrice);
            expPriceOld.setTradePrice(expPrice.getTradePrice());
            expPriceOld.setRetailPrice(expPrice.getRetailPrice());
            num = expPriceModify(expPrice, expPriceOld, expInfo, num);
        }
        return num;
    }

    /**
     * 消耗品调价方法
     * expPrice前台修改的价格记录
     * expPriceModify要修改的价格记录
     * expInfo要修改的价表对应的expInfo
     *
     * @author zhuq
     */
    private int expPriceModify(ExpPrice expPrice, ExpPrice expPriceModify, ExpInfo expInfo, int num) {

        //1.修改expPrice表
        expPriceModify.setStartDate(expPrice.getStartDate());
        expPriceModify.preUpdate();
        num = num * dao.update(expPriceModify);
        /**创建定时任务 create by CTQ at 2017-07-09 09:29:51**/
        dao.createEventTask(UserUtils.getOrgId(), DateFormatUtils.format(expPrice.getStartDate(),"yyyyMMddHHmmss"),DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"),expPrice.getId());

        //2.获取expPriceLog表的记录,然后新增一条，修改一条
        ExpPriceLog expPriceLogOld = new ExpPriceLog();
        expPriceLogOld.setExpPriceId(expPriceModify.getId());
        List<ExpPriceLog> list=expPriceLogDao.findByPriceId(expPriceLogOld);
        if(list.size()!=0){
            expPriceLogOld = expPriceLogDao.findByPriceId(expPriceLogOld).get(0);
        }
        /**3.修改药品价格日志表，修改价表停止时间及是否最新价表标识**/
        expPriceLogDao.updateByExpPriceId(expPriceModify.getId(),Global.NO,expPrice.getStartDate());
        ExpPriceLog expPriceLogNew = new ExpPriceLog();
        expPriceLogNew = expPriceLogOld;
        expPriceLogNew.setId(null);
        expPriceLogNew.setRetailPrice(expPriceModify.getRetailPrice());
        expPriceLogNew.setTradePrice(expPriceModify.getTradePrice());
        expPriceLogNew.setStartDate(expPrice.getStartDate());
        expPriceLogNew.setStopDate(expPrice.getStopDate());
        expPriceLogNew.setIsNew(Global.YES);
        expPriceLogNew.preInsert();
        num = num * expPriceLogDao.insert(expPriceLogNew);

        //4.修改priceList表
        PriceList priceList = new PriceList();
        priceList = priceListDao.get(expPriceModify.getPriceList());
        priceList.setStartDate(expPriceModify.getStartDate());
        priceList.setPrice(expPriceModify.getRetailPrice());
        priceList.setPreferPrice(expPriceModify.getRetailPrice());
        priceList.preUpdate();
        num = num * priceListDao.update(priceList);

        //5.修改priceListLog表，新增一条修改一条
        PriceListLog priceListLogOld = new PriceListLog();
        priceListLogOld.setPriceId(priceList.getId());



        List<PriceListLog> listLogs= priceListLogDao.findByPriceId(priceListLogOld);
        if(listLogs!=null && listLogs.size()!=0){
            priceListLogOld = priceListLogDao.findByPriceId(priceListLogOld).get(0);

            /**6.更新price_list_log中id=此记录ID and is_ner='1' and stop_date is null的stop_date和is_ner=0**/
            priceListLogDao.updateByPriceId(priceList.getId(), Global.NO, expPrice.getStartDate());


            PriceListLog priceListLogNew = new PriceListLog();
            priceListLogNew = priceListLogOld;
            priceListLogNew.setId(null);
            priceListLogNew.setPrice(expPriceModify.getRetailPrice());
            priceListLogNew.setPreferPrice(expPriceModify.getTradePrice());
            priceListLogNew.setStartDate(expPriceLogNew.getStartDate());
            priceListLogNew.setStopDate(null);
            /**7 1:是最新价表0：不是最新价表 add by CTQ at 2017-07-05 09:18:55**/
            priceListLogNew.setIsNer(Global.YES);
            priceListLogNew.preInsert();
            num = num * priceListLogDao.insert(priceListLogNew);
        }


        return num;
    }

    /**
     * 调价时只获取最大包装
     *
     * @author zhuq
     */
    @Transactional(readOnly = false)
    public Page<ExpPrice> findByMaxSpec(Page<ExpPrice> page, ExpPrice expPrice) {
        expPrice.updateOrgId();
        expPrice.setPage(page);
        page.setList(dao.findByMaxSpec(expPrice));
        return page;
    }

    /**
     * 消耗品停价功能
     *
     * @param expPrice
     * @return
     * @author fengyg
     */
    @Transactional(readOnly = false)
    public StringData stopPrice(ExpPrice expPrice) {
        int i = 0;
        StringData data = new StringData();
        List<ExpPrice> expPrices = dao.findByExpInfo(expPrice);  //大小包装价格
        List<String> priceIds = new ArrayList<String>();    //存放价表price_list的ID
        ExpStock stock = new ExpStock();
        stock.setInfoId(expPrice.getExpInfo().getId());
        stock.setOrgId(expPrice.getOrgId());
        List<ExpStock> stocks = expStockDao.getList(stock);
        if (null != stocks && stocks.size() > 0) {//有库存，不能停价
            data.setCode("info");
            data.setData("该消耗品还有库存, 不能停价!!");
        } else {//停价
            if (null != expPrices && expPrices.size() > 0) {
                for (ExpPrice price : expPrices) {
                    Date date = new Date();
                    /**1.判断开始时间是否大于停止时间，如果大于停止时间，则修改开始时间与停止时间一致 add by CTQ at 2017-07-05 14:23:52**/
                    if (price.getStartDate().after(date)){
                        price.setStartDate(date);
                    }
                    price.setStopDate(date);
                    priceIds.add(price.getPriceList().getId());
                    i += dao.update(price);
                    /**2.根据exp_price表的id查询exp_price_log**/
                    ExpPriceLog expPriceLog = new ExpPriceLog();
                    expPriceLog.setExpPriceId(price.getId());
                    /**3.停用药品价表日志记录update by CTQ at 2017-07-05 14:23:43 **/
                    expPriceLogDao.updateByExpPriceId(price.getId(),Global.NO,price.getStopDate());

                    //根据exp_price表的price_id查询price_list表数据
                    PriceList priceList = new PriceList();
                    priceList.setId(price.getPriceList().getId());
                    PriceList priceList1 = priceListDao.get(priceList);
                    if (null != priceList1) {
                        //设置price_list表的stopDate
                        if (priceList1.getStartDate().after(date)){
                            priceList1.setStartDate(date);
                        }
                        priceList1.setStopDate(date);
                        priceList1.setDelFlag(BaseEntity.DEL_FLAG_DELETE);
                        i += priceListDao.update(priceList1);

                        /**5.停掉调价记录数据 update by CTQ at 2017-07-05 14:23:38 **/
                        priceListLogDao.updateByPriceId(priceList1.getId(), Global.NO, priceList1.getStopDate());
                    }
                }
            }
            if (i > 0) {
                data.setCode("success");
                data.setData("停价成功!");
            } else {
                data.setCode("error");
                data.setData("停价失败!");
            }
        }
        return data;
    }
}